<!-- 训练试卷详情页 -->
<template>
  <div class="app-container">
    <!-- 试卷信息 -->
    <div class="paper-header">
      <div class="paper-info">
        <h2>{{ paper.paperName }}</h2>
        <div class="paper-meta">
          <span>总分：{{ paper.totalScore }}分</span>
          <span>得分：{{ statistics.totalScore }}分</span>
          <span>题目数：{{ questions.length }}题</span>
          <span
            >来源：{{
              paper.sourceType === "WRONG_QUESTIONS" ? "错题训练" : "随机训练"
            }}</span
          >
          <span>完成时间：{{ paper.updatedTime }}</span>
        </div>
      </div>
      <div class="paper-actions">
        <el-button @click="handleBack">返回列表</el-button>
      </div>
    </div>

    <el-row :gutter="20" class="paper-content">
      <!-- 题目列表 -->
      <el-col :span="18">
        <div
          v-for="(question, index) in questions"
          :key="question.id"
          class="question-item"
          :class="{ 'is-correct': questionResults[question.id]?.isCorrect }"
        >
          <div class="question-header">
            <div class="question-info">
              <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">[单选题]</span>
              <span class="question-score">{{ question.score }}分</span>
            </div>
            <div class="question-result">
              <el-tag
                :type="
                  questionResults[question.id]?.isCorrect ? 'success' : 'danger'
                "
              >
                {{ questionResults[question.id]?.isCorrect ? "正确" : "错误" }}
              </el-tag>
            </div>
          </div>

          <div class="question-content">{{ question.questionText }}</div>

          <div class="question-options">
            <div
              v-for="(option, key) in parseOptions(question.options)"
              :key="key"
              class="option-item"
              :class="{
                'is-selected': questionResults[question.id]?.userAnswer === key,
                'is-correct': question.correctAnswer === key,
              }"
            >
              <span class="option-key">{{ key }}.</span>
              <span class="option-content">{{ option }}</span>
              <span class="option-indicator">
                <el-icon
                  v-if="questionResults[question.id]?.userAnswer === key"
                >
                  <component
                    :is="
                      question.correctAnswer === key
                        ? 'CircleCheck'
                        : 'CircleClose'
                    "
                  />
                </el-icon>
                <el-icon v-else-if="question.correctAnswer === key">
                  <CircleCheck />
                </el-icon>
              </span>
            </div>
          </div>

          <div class="question-analysis">
            <div class="analysis-item">
              <span class="label">你的答案：</span>
              <span
                :class="{
                  'text-danger': !questionResults[question.id]?.isCorrect,
                }"
              >
                {{ questionResults[question.id]?.userAnswer || "未作答" }}
              </span>
            </div>
            <div class="analysis-item">
              <span class="label">正确答案：</span>
              <span class="text-success">{{ question.correctAnswer }}</span>
            </div>
          </div>
        </div>
      </el-col>

      <!-- 统计信息 -->
      <el-col :span="6">
        <div class="statistics-card">
          <h3>答题统计</h3>
          <div class="statistics-content">
            <div class="statistics-item">
              <span class="label">总分</span>
              <span class="value">{{ statistics.totalScore }}</span>
            </div>
            <div class="statistics-item">
              <span class="label">正确题数</span>
              <span class="value text-success">{{
                statistics.correctCount
              }}</span>
            </div>
            <div class="statistics-item">
              <span class="label">错误题数</span>
              <span class="value text-danger">{{ statistics.wrongCount }}</span>
            </div>
            <div class="statistics-item">
              <span class="label">正确率</span>
              <span class="value">{{ statistics.accuracy }}%</span>
            </div>
          </div>

          <!-- 正确率图表 -->
          <div class="chart-container">
            <div
              ref="accuracyChartRef"
              style="width: 100%; height: 200px"
            ></div>
          </div>

          <!-- 得分分布图表 -->
          <div class="chart-container">
            <div ref="scoreChartRef" style="width: 100%; height: 200px"></div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import {
  getTrainingPaperDetail,
  getTrainingPaperQuestions,
  getTrainingPaperResults,
} from "@/api/training";

const route = useRoute();
const router = useRouter();

// 图表引用
const accuracyChartRef = ref(null);
const scoreChartRef = ref(null);

// 数据
const paper = ref({});
const questions = ref([]);
const questionResults = reactive({});

// 统计信息
const statistics = reactive({
  totalScore: 0,
  correctCount: 0,
  wrongCount: 0,
  accuracy: 0,
});

// 添加解析选项的方法
const parseOptions = (optionsStr) => {
  try {
    // 将字符串按换行符分割成数组
    const optionArray = optionsStr.split("\n");
    // 创建选项对象
    const optionsObj = {};
    optionArray.forEach((option) => {
      // 分割选项标识和内容 (例如: "A.选项内容" => ["A", "选项内容"])
      const [key, ...content] = option.split(".");
      optionsObj[key] = content.join("."); // 重新组合内容，以防选项内容中包含点号
    });
    return optionsObj;
  } catch (error) {
    console.error("选项解析失败:", error);
    return {}; // 返回空对象作为默认值
  }
};

// 获取试卷信息
const getPaper = async () => {
  try {
    const paperId = route.params.id;
    const [paperData, questionList, resultList] = await Promise.all([
      getTrainingPaperDetail(paperId),
      getTrainingPaperQuestions(paperId),
      getTrainingPaperResults(paperId),
    ]);

    // 如果试卷未完成，跳转到答题页
    if (paperData.status === 0) {
      ElMessage.warning("试卷未完成");
      router.replace(`/training/paper/${paperId}`);
      return;
    }

    paper.value = paperData;
    questions.value = questionList;

    // 重置统计信息
    statistics.totalScore = 0;
    statistics.correctCount = 0;
    statistics.wrongCount = 0;

    // 将答题结果转换为Map格式，方便查找
    const resultMap = {};
    resultList.forEach((result) => {
      resultMap[result.questionId] = {
        userAnswer: result.userAnswer,
        isCorrect: result.isCorrect,
      };
    });

    // 处理答题结果
    questionList.forEach((question) => {
      const result = resultMap[question.id];
      if (!result) return;

      questionResults[question.id] = result;

      // 更新统计信息
      if (result.isCorrect) {
        statistics.correctCount++;
        statistics.totalScore += question.score;
      } else {
        statistics.wrongCount++;
      }
    });

    // 计算正确率
    statistics.accuracy =
      questions.value.length > 0
        ? Math.round((statistics.correctCount / questions.value.length) * 100)
        : 0;

    // 初始化图表
    nextTick(() => {
      initCharts();
    });
  } catch (error) {
    console.error("获取试卷信息失败：", error);
    ElMessage.error("获取试卷信息失败");
  }
};

// 初始化图表
const initCharts = () => {
  // 正确率图表
  const accuracyChart = echarts.init(accuracyChartRef.value);
  accuracyChart.setOption({
    title: {
      text: "正确率",
      left: "center",
    },
    series: [
      {
        type: "gauge",
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 10,
        itemStyle: {
          color: "#58D9F9",
        },
        progress: {
          show: true,
          roundCap: true,
          width: 18,
        },
        pointer: {
          show: false,
        },
        axisLine: {
          roundCap: true,
          lineStyle: {
            width: 18,
          },
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
        },
        axisLabel: {
          show: false,
        },
        title: {
          show: false,
        },
        detail: {
          valueAnimation: true,
          offsetCenter: [0, "20%"],
          fontSize: 30,
          formatter: "{value}%",
        },
        data: [
          {
            value: statistics.accuracy,
          },
        ],
      },
    ],
  });

  // 得分分布图表
  const scoreChart = echarts.init(scoreChartRef.value);
  scoreChart.setOption({
    title: {
      text: "得分分布",
      left: "center",
    },
    tooltip: {
      trigger: "item",
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          {
            value: statistics.correctCount,
            name: "正确",
            itemStyle: { color: "#67C23A" },
          },
          {
            value: statistics.wrongCount,
            name: "错误",
            itemStyle: { color: "#F56C6C" },
          },
        ],
      },
    ],
  });

  // 监听窗口大小变化
  window.addEventListener("resize", () => {
    accuracyChart.resize();
    scoreChart.resize();
  });
};

// 返回列表
const handleBack = () => {
  router.push("/training/list");
};

onMounted(() => {
  getPaper();
});
</script>

<style scoped>
.paper-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.paper-info h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.paper-meta {
  color: #666;
  font-size: 14px;
}

.paper-meta span {
  margin-right: 20px;
}

.paper-content {
  margin-top: 20px;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-left: 4px solid transparent;
}

.question-item.is-correct {
  border-left-color: #67c23a;
}

.question-item:not(.is-correct) {
  border-left-color: #f56c6c;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.question-index {
  font-weight: bold;
  margin-right: 10px;
}

.question-type {
  color: #666;
  margin-right: 10px;
}

.question-score {
  color: #f56c6c;
}

.question-content {
  margin-bottom: 15px;
  line-height: 1.6;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  transition: all 0.3s;
}

.option-item.is-selected {
  background-color: #fef0f0;
}

.option-item.is-correct {
  background-color: #f0f9eb;
}

.option-key {
  margin-right: 10px;
  font-weight: bold;
}

.option-content {
  flex: 1;
}

.option-indicator {
  margin-left: 10px;
}

.question-analysis {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.analysis-item {
  margin-bottom: 10px;
}

.analysis-item .label {
  color: #666;
  margin-right: 10px;
}

.statistics-card {
  position: sticky;
  top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.statistics-card h3 {
  margin: 0 0 20px 0;
  font-size: 16px;
}

.statistics-content {
  margin-bottom: 20px;
}

.statistics-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.statistics-item .label {
  color: #666;
}

.statistics-item .value {
  font-size: 18px;
  font-weight: bold;
}

.chart-container {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.text-success {
  color: #67c23a;
}

.text-danger {
  color: #f56c6c;
}
</style>
